package core.android.tools;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者: XQ
 * @创建时间：2016/7/29 8:50
 * @类说明: webview通用配置工具
 */
public class AKWebViewUtil {
    private Map<String, String> extraHeaders = new HashMap<String, String>();
    private WebView mWebView;
    private View loadingTip;//加载中提示
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress > 95) {
                if (loadingTip != null) loadingTip.setVisibility(View.GONE);

            } else {
                if (loadingTip != null) loadingTip.setVisibility(View.VISIBLE);
            }
        }
    };
    private WebViewClient mWebViewClient = new WebViewClient() {

        /**
         * 多页面在同一个WebView中打开，就是不新建activity或者调用系统浏览器打开
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("https://mapi.alipay.com")) {
                AK.e("吊起支付宝链接："+url);
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    intent.addCategory("android.intent.category.BROWSABLE");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    AKActivityUtil.INSTANCE.getApplication().startActivity(intent);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mWebView.loadUrl(url, extraHeaders);
            }
            return true;
        }
    };

    public AKWebViewUtil(WebView mWebView, View loadingTip) {
        this.mWebView = mWebView;
        this.loadingTip = loadingTip;
        initWebView();
    }

    public AKWebViewUtil(WebView mWebView) {
        this(mWebView, null);
    }

    /**
     * webview头
     */
    public Map<String, String> getExtraHeaders() {
        return extraHeaders;
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebView() {
        if (mWebView == null) {
            Log.e(getClass().getSimpleName(), "mWebView is null！");
            return;
        }
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setLoadsImagesAutomatically(true);

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        /*mWebView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                if (v instanceof WebView) {
                    WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                    if (result != null) {
                        int type = result.getType();
                        if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                            pictureUrl = result.getExtra();
                            KLog.d("长按图片地址pictureUrl=：" + pictureUrl);
                            btn_save();
                        }
                    }
                }
            }
        });*/
    }

    public void setWebViewClient(WebViewClient webViewClient) {
        this.mWebViewClient = webViewClient;
        if (this.mWebViewClient != null) mWebView.setWebViewClient(this.mWebViewClient);
    }

    public void setmWebChromeClient(WebChromeClient mWebChromeClient) {
        this.mWebChromeClient = mWebChromeClient;
        if (this.mWebChromeClient != null) mWebView.setWebChromeClient(this.mWebChromeClient);
    }

    /**
     * webview加载内容
     */
    public void loadUrl(String mUrl) {
        if (mUrl != null) mWebView.loadUrl(mUrl, extraHeaders);
    }

    /**
     * webview加载内容
     */
    public void loadDataWithBaseURL(String mHtml) {
        if (mHtml != null) mWebView.loadDataWithBaseURL(null, mHtml, "text/html", "utf-8", null);
    }

    /**
     * 设置cookie
     *
     * @param yuming   zcwdapi.renrenweidian.com
     * @param keyValue userid=john
     */
    private void setCookie(String yuming, String keyValue) {//成功
        CookieSyncManager.createInstance(mWebView.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(yuming, keyValue);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        }
    }

    /**
     * HTML5数据存储
     */
    public void setWebviewCache() {
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        String appCachePath = mWebView.getContext().getCacheDir().getAbsolutePath();
        mWebView.getSettings().setAppCachePath(appCachePath);
    }


    /**
     * 清理cookie
     */
    public void clearCookie() {
        CookieSyncManager.createInstance(mWebView.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();
    }


    /**
     * 安全销毁Webview
     */
    public void safeDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
    }
}
